#! /usr/bin/env pytho
import weakref
import logging
from PyQt4 import QtCore

class QtSignalEmitter:
    """Allow any subclass to emit Qt signals without inheriting from QObject.
    This class was inspired by the solution presented at the  following site:

    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/361527

    The following example illustrate how a subclass can utilize the
    Emitter() method provided by this class to emit signals that can
    be used by other Qt classes.

    from PyQt4 import QtCore
    class Foo( QtSignalEmitter ):
        #
        # The following method performs some operation and emits a signal
        # once the operation is complete.
        #
        def PerformSomeOperation( self ):
            self.SomeOperation()   
            QtCore.QObject.emit( self.Emitter(), 
                                 QtCore.SIGNAL( 'operationFinished' ) )
            return
       def SomeOperation( self ):
            return
    #
    # Now one can connect the 'operationFinished' signal to a slot as
    # follows.
    #    
    Foo my_foo 
    QtCore.QObject.connect( my_foo.Emitter(),
                            QtCore.SIGNAL( 'operationFinished' ),
                            app,
                            QtCore.SLOT( 'quit()' ) )
    """
    __mEmitterCache = weakref.WeakKeyDictionary()
    def __init__( self ):
        return 
    def Emitter( self ):
        """Returns a QObject surrogate for the current object to use in Qt signaling.
        
        This approach enables you to connect to and emit signals from (almost)
        any python object with having to subclass QObject.
        
        >>> class A(object):
        ...   def notify(self, *args):
        ...       QObject.emit(emitter(self), PYSIGNAL('test'), args)
        ...
        >>> ob = A()
        >>> def myhandler(*args): print 'got', args
        ...
        >>> QObject.connect(emitter(ob), PYSIGNAL('test'), myhandler)
        ... True
        >>> ob.notify('hello')
        got ('hello',)
        
        >>> QObject.emit(emitter(ob), PYSIGNAL('test'), (42, 'abc',))
        got (42, 'abc')
        """
        if self not in QtSignalEmitter.__mEmitterCache:
            QtSignalEmitter.__mEmitterCache[self] = QtCore.QObject()
        return QtSignalEmitter.__mEmitterCache[self]
#
# -----------------------------------------------------------------
if __name__ == "__main__":
    try:
        my_signal_emitter = QtSignalEmitter()
    except SystemExit:
        raise
    except:
        print \
"""An internal error occured.  Please report all the output from the program,
including the following traceback.
"""
        raise
